未分類

Number of Segments in a String

Number of Segments in a String

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

For Example:

1
2
Input: "Hello, my name is John"
Output: 5
提示 解題應用
String 規律觀查

Default:

1
2
3
func countSegments(s string) int {
}

解答思路:

這題最主要是一定要先看到非空格的值,之後出現空格才將計數+1,如果只看空格有多少個,會因為參數只有滿滿的空格而誤判,而如果有非語系的特殊符號因為無法顯示也可能會產生空格,不過題目這邊就有強調不會包含任何印不出的字元,所以可以放心。

程式碼解說:

一開始先利用迴圈一一取出字串中的字元,並將rune值轉為字串,接著當該字串非為空格時先做個註記,直到出現的字元為空格且先前已經有非空格的註記時,這時我們才把計數+1,並把notSpace改回false重新計算下一個單字直到遍歷結束,不過可能會發生該單字在字串的結尾,沒有了空格因而少算了一個單字,所以最後要再次判斷notSpace的註記是否為true,如果是就將結果+1再回傳,否則就直接回傳結果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var str string
var count int
var notSpace bool
for _, v := range s {
str = string(v)
if str != " " {
notSpace = true
} else if str == " " && notSpace {
count++
notSpace = false
}
}
if notSpace {
return count + 1
}
return count

完整程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func countSegments(s string) int {
var str string
var count int
var notSpace bool
for _, v := range s {
str = string(v)
if str != " " {
notSpace = true
} else if str == " " && notSpace {
count++
notSpace = false
}
}
if notSpace {
return count + 1
}
return count
}

總結:

要判斷一字串中有多少個單字,最主要就是一定要先看到非空格的值,之後出現空格才將計數+1,如果只看空格有多少個,會因為參數只有滿滿的空格而誤判。

分享到